package service.impl;

import dao.CardDao;
import entity.Card;
import org.apache.ibatis.session.SqlSession;
import service.CardService;
import utils.MybatisUtil;

import java.util.List;

public class CardServiceImpl implements CardService {
    @Override
    public List<Card> selectList(int startIndex, int pageSize) {
        SqlSession sqlSession = MybatisUtil.createSqlSession();
        CardDao dao = sqlSession.getMapper(CardDao.class);
        List<Card> cards = null;
        try{
            cards =dao.selectList(startIndex,pageSize);
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            MybatisUtil.closeSqlSession(sqlSession);
        }
        return cards;
    }

    @Override
    public int selectListSize() {
        SqlSession sqlSession = MybatisUtil.createSqlSession();
        CardDao dao = sqlSession.getMapper(CardDao.class);
        int r = 0;
        try{
            r =dao.selectListSize();
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            MybatisUtil.closeSqlSession(sqlSession);
        }
        return r;
    }

    @Override
    public int add(Card card) {
        SqlSession sqlSession = MybatisUtil.createSqlSession();
        CardDao dao = sqlSession.getMapper(CardDao.class);
        int r = 0;
        try {
            r = dao.add(card);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            MybatisUtil.closeSqlSession(sqlSession);
        }
        return r;
    }

    @Override
    public int update(int id, int status) {
        SqlSession sqlSession = MybatisUtil.createSqlSession();
        CardDao dao = sqlSession.getMapper(CardDao.class);
        int r = 0;
        try {
            r = dao.update(id,status);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            MybatisUtil.closeSqlSession(sqlSession);
        }
        return r;
    }

    @Override
    public int delete(int id) {
        SqlSession sqlSession = MybatisUtil.createSqlSession();
        CardDao dao = sqlSession.getMapper(CardDao.class);
        int r = 0;
        try {
            r = dao.delete(id);
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            MybatisUtil.closeSqlSession(sqlSession);
        }
        return r;
    }
}
